package org.ypx.center.controller.impl;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.ypx.center.service.IUserService;
import org.ypx.db.entity.User;

/**
 * @author Yan Peixuan
 * @date 2017/3/28 21:06
 * @description
 */
@Controller
@RequestMapping("login")
public class LoginControllerImpl {
    @Autowired
    private IUserService userService;

    @RequestMapping("login.do")
    @ResponseBody
    public ModelAndView login(@RequestParam("loginName") String loginName, @RequestParam("password") String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(loginName, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (IncorrectCredentialsException ice) {
            // 捕获密码错误异常
            ModelAndView mv = new ModelAndView("error");
            mv.addObject("message", "password error!");
            return mv;
        } catch (UnknownAccountException uae) {
            // 捕获未知用户名异常
            ModelAndView mv = new ModelAndView("error");
            mv.addObject("message", "loginName error!");
            return mv;
        } catch (ExcessiveAttemptsException eae) {
            // 捕获错误登录过多的异常
            ModelAndView mv = new ModelAndView("error");
            mv.addObject("message", "times error");
            return mv;
        }
        String page = "";
        if (subject.hasRole("admin")) {
            page = "index";
        }
        if (subject.hasRole("teacher")) {
            page = "index2";
        }
        if (subject.hasRole("student")) {
            page = "index3";
        }
        User user = userService.findByLoginName(loginName);
        subject.getSession().setAttribute("user", user);
        return new ModelAndView(page);
    }


}
